<template>
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="6" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="height: 96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
            <el-tree
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              highlight-current
              v-loading="treeLoading"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node" style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <span>{{ node.label }}</span>
                  <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <el-col :span="18" style="height: 100%;background-color: #FFFFFF;padding: 10px;">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                     :label-width="labelWidth">
              <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                <el-form-item label="用户名称" prop="userName">
                  <el-input
                    v-model="queryParams.userName"
                    placeholder="请输入用户名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="用户编号" prop="userId">
                  <el-input
                    v-model="queryParams.userId"
                    placeholder="请输入用户编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="设备编号" prop="terminalId">
                  <el-input
                    v-model="queryParams.terminalId"
                    placeholder="请输入设备编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="所属客户" prop="tenantId">
                  <el-select filterable v-model="queryParams.tenantId" placeholder="请选择所属客户"
                             style="width: 100%;">
                    <el-option
                      v-for="dept in deptOption"
                      :key="dept.tenantId"
                      :label="dept.deptName"
                      :value="dept.tenantId"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="注册平台" prop="signPlatform">
                  <el-select filterable clearable v-model="queryParams.signPlatform" placeholder="请选择注册平台" style="width: 100%;">
                    <el-option v-for="dict in dict.type.sign_platform" :key="dict.value" :label="dict.label"
                               :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="通讯类型" prop="communicationType">
                  <el-select filterable v-model="queryParams.communicationType" placeholder="请选择通讯类型" style="width: 100%;">
                    <el-option v-for="dict in dict.type.communication_type" :key="dict.value" :label="dict.label"
                               :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="绑定状态" prop="isBound">
                  <el-select clearable v-model="queryParams.isBound" placeholder="请选择绑定状态" style="width: 100%;">
                    <el-option
                      v-for="dict in dict.type.bind_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="使用状态" prop="terminalMark">
                  <el-select v-model="queryParams.terminalMark" placeholder="请选择使用状态" style="width: 100%;">
                    <el-option
                      v-for="dict in dict.type.used_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form>
          </el-col>

          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:terminalxb:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:terminalxb:remove']"
            >批量删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-has-permi="['basedata:terminalxb:import']"
            >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleBatchUpdate"
              v-has-permi="['basedata:ternimalxb:batchUpdate']"
            >批量更新
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleRegister"
              v-has-permi="['basedata:terminalxb:createGuoXinDeviceInAep']"
            >NB平台注册
            </el-button>
          </el-col>

          <RightDropdown :columns="columns" :showSearch.sync="showSearch"
                         @queryTable="getList" @export="handleExport"
                         :hasPermiExport="['basedata:terminalxb:export']"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="terminalxbList" size="mini" row-key="id" border
                   @selection-change="handleSelectionChange" default-expand-all :height="getAvailableHeight"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :default-sort="defaultSort"
                  @sort-change="handleSorterChange"  >
          <el-table-column type="selection" width="55" align="center" :selectable="selectable"/>
          <el-table-column label="设备编号" align="center" prop="terminalId" v-if="columns[2].visible"
                           :show-overflow-tooltip="true" width="120" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <router-link :to="{name: 'HistoryXb', params: {locationNb: scope.row.locationNb,terminalId: scope.row.terminalId}}"><span style="color: #00afff">{{scope.row.terminalId}}</span></router-link>
            </template>
          </el-table-column>
          <el-table-column label="设备名称" align="center" prop="installAddress" v-if="columns[17].visible"
                           :show-overflow-tooltip="true" width="180" 
                          />

          <el-table-column label="区域名称" align="center" prop="sheetsName" v-if="columns[18].visible"
                           :show-overflow-tooltip="true" width="120" 
            />


          <!-- <el-table-column label="设备归属水司" align="center" prop="tenantId" width="120" v-if="columns[1].visible" :show-overflow-tooltip="true"/> -->
        
          <!--          <el-table-column label="门牌号" align="center" prop="installAddress" v-if="columns[2].visible" width="90"-->
          <!--                           :show-overflow-tooltip="true" sortable="custom" :sort-orders="['ascending', 'descending']"/>-->
          <el-table-column label="IMEI" align="center" prop="imei" v-if="columns[3].visible"
                           :show-overflow-tooltip="true" width="150" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <!-- <el-table-column label="楼栋编号" align="center" prop="ldId" v-if="false" :show-overflow-tooltip="true"/>
          <el-table-column label="房间号" align="center" prop="roomId" v-if="false" :show-overflow-tooltip="true"/> -->
          <el-table-column label="厂家名称" align="center" prop="supplierId" v-if="columns[4].visible"
                           :show-overflow-tooltip="true" width="100" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.supplierId"/>
            </template>
          </el-table-column>
         
          <el-table-column label="表底数" align="center" prop="baseReading" v-if="columns[6].visible"
                           :show-overflow-tooltip="true" width="90" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <!-- (0：否，1：是) -->
          <el-table-column label="是否带阀控" align="center" prop="valveControl" width="110" v-if="columns[7].visible"
                           :show-overflow-tooltip="true" sortable="custom" :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yes_no" :value="scope.row.valveControl"/>
            </template>
          </el-table-column>
          <el-table-column label="表解析地址" align="center" prop="communicateAddress" v-if="columns[13].visible"
                           :show-overflow-tooltip="true" width="150" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="表状态" align="center" prop="terminalMark" v-if="columns[11].visible"
                           :show-overflow-tooltip="true" width="90" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.used_status" :value="scope.row.terminalMark"/>
            </template>
          </el-table-column>
          <el-table-column label="协议名称" align="center" prop="protocolName" v-if="columns[12].visible"
                           :show-overflow-tooltip="true" width="130" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
           <el-table-column label="表型号" align="center" prop="typeId" v-if="columns[5].visible"
                           :show-overflow-tooltip="true" width="120" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.module_type" :value="scope.row.typeId"/>
            </template>
          </el-table-column>                 
          <!-- <el-table-column label="用户名称" align="center" prop="userName" v-if="columns[0].visible"
                           :show-overflow-tooltip="true" width="130" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="用户编号" align="center" prop="userId" v-if="columns[1].visible"
                           :show-overflow-tooltip="true" sortable="custom" width="100"
                           :sort-orders="['ascending', 'descending']"/> -->
          <el-table-column label="阀门地址" align="center" prop="valveAddress" v-if="columns[8].visible" width="100"
                           :show-overflow-tooltip="true" sortable="custom" :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="安装日期" align="center" prop="installDate" v-if="columns[9].visible" width="100"
                           :show-overflow-tooltip="true" sortable="custom" :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.installDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!--      <el-table-column label="安装地址" align="center" prop="installAddress" v-if="columns[11].visible"-->
          <!--                       :show-overflow-tooltip="true"/>-->
          <el-table-column label="抄表周期" align="center" prop="meterReaderCycle" width="100"
                           v-if="columns[10].visible" :show-overflow-tooltip="true" sortable="custom"
                           :sort-orders="['ascending', 'descending']">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.reader_cycle" :value="scope.row.meterReaderCycle"/>
            </template>
          </el-table-column>
          
          <el-table-column label="通讯类型" align="center" prop="communicationType" v-if="columns[16].visible"
                           :show-overflow-tooltip="true" width="90">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.communication_type" :value="scope.row.communicationType"/>
            </template>
          </el-table-column>
<!--          <el-table-column label="注册平台" align="center" prop="signPlatform" v-if="columns[17].visible"-->
<!--                           :show-overflow-tooltip="true" width="90">-->
<!--            <template slot-scope="scope">-->
<!--              <dict-tag :options="dict.type.sign_platform" :value="scope.row.signPlatform"/>-->
<!--            </template>-->
<!--          </el-table-column>-->
          
          <el-table-column label="集中器" align="center" prop="concentratorName" v-if="columns[14].visible"
                           :show-overflow-tooltip="true" width="100" sortable="custom"
                           :sort-orders="['ascending', 'descending']"/>
          <el-table-column label="所属客户" align="center" prop="deptName" v-if="columns[15].visible"
                           :show-overflow-tooltip="true" width="100"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
            <template slot-scope="scope">
<!--              <el-tooltip effect="dark" content="详情" placement="top">-->
<!--                <el-button-->
<!--                  size="mini"-->
<!--                  type="text"-->
<!--                  icon="el-icon-view"-->
<!--                  @click="handleDetail(scope.row)"-->
<!--                  v-hasPermi="['basedata:usersxb:edit']"-->
<!--                >-->
<!--                </el-button>-->
<!--              </el-tooltip>-->
              <el-tooltip effect="dark" content="修改" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-show="scope.row.terminalMark === 1"
                  v-hasPermi="['basedata:terminalxb:edit']"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="换表" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-sort"
                  v-show="scope.row.terminalMark === 1"
                  v-hasPermi="['basedata:terminalxb:changeTerminalXb']"
                  @click="handleReplaceTerminal(scope.row)"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="销表" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-coordinate"
                  v-show="scope.row.terminalMark === 1"
                  @click="handledeleteterminal(scope.row)"
                  v-hasPermi="['basedata:terminalxb:cancelTerminal']"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="表过户" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-user"
                  v-hasPermi="['basedata:ternimalxb:changeUser']"
                  v-show="scope.row.terminalMark === 1 && scope.row.userId !== null"
                  @click="handleTransferUser(scope.row)"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['basedata:usersxb:remove']"
                  v-if="scope.row.terminalMark === 1"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="开阀" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-unlock"
                  @click="handleOpenValve(scope.row)"
                  v-show="scope.row.terminalMark === 1"
                  v-hasPermi="['basedata:termianlxb:terminalXbCommand']"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="关阀" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-lock"
                  @click="handleCloseValve(scope.row)"
                  v-show="scope.row.terminalMark === 1"
                  v-hasPermi="['basedata:termianlxb:terminalXbCommand']"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <el-dialog title="户表详情" :visible.sync="detailVisible" width="1200px" :close-on-click-modal="false"
                   fullscreen
                   append-to-body @close="handleDetailClose">
          <el-tabs v-model="tabActiveKey" type="card" @tab-click="handleTabClick">
            <el-tab-pane label="实时数据" name="1">
              <RealTime ref="refMeterRealTime" v-if="tabActiveKey==='1'"/>
            </el-tab-pane>
            <el-tab-pane label="用量统计" name="2">
              <Dosage ref="refMeterDosage" v-if="tabActiveKey==='2'"/>
            </el-tab-pane>
            <el-tab-pane label="历史数据" name="3">
              <History ref="refMeterHistory" v-if="tabActiveKey==='3'"/>
            </el-tab-pane>
            <el-tab-pane label="日志记录" name="4">
              <Log ref="refMeterLog" v-if="tabActiveKey==='4'"/>
            </el-tab-pane>
            <el-tab-pane label="报警记录" name="5">
              <Alarm ref="refMeterAlarm" v-if="tabActiveKey==='5'"/>
            </el-tab-pane>
          </el-tabs>
        </el-dialog>

        <!-- 添加或修改已绑定户表档案对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="840px" append-to-body>
          <el-form ref="formXb" :model="form" :rules="rules" label-width="150px" :inline="true">
            <el-form-item label="设备编号" prop="terminalId">
              <el-input v-model="form.terminalId" placeholder="请输入设备编号"/>
            </el-form-item>
            <el-form-item label="IMEI" prop="imei">
              <el-input v-model="form.imei" placeholder="请输入IMEI" :disabled="title === '修改户表档案' ? true : false"/>
            </el-form-item>
            <el-form-item label="厂家名称" prop="supplierId">
              <el-select v-model="form.supplierId" filterable placeholder="请输入厂家名称" style="width: 202px;">
                <el-option
                  v-for="dict in dict.type.terminal_supplier"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表型号" prop="typeId">
              <el-select v-model="form.typeId" filterable placeholder="请选择表型号" clearable style="width: 202px;">
                <el-option
                  v-for="dict in dict.type.module_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表底数" prop="baseReading">
              <el-input v-model="form.baseReading" placeholder="请输入表底数"/>
            </el-form-item>
             <el-form-item label="能耗分项" prop="energyUseItem">
              <el-select v-model="form.energyUseItem" placeholder="请选择能耗分项" style="width: 202px;">
                <el-option v-for="dict in dict.type.energy_use_item" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="用户编号" prop="userId"> -->
<!--              <el-select v-model="form.userId" filterable style="width: 202px;">-->
<!--                <el-option v-for="user in usersXbList" :key="user.userId" :value="user.userId"-->
<!--                           :label=" user.userId + '：' + user.userName ">-->
<!--                </el-option>-->
<!--              </el-select>-->
              <!-- <el-input v-model="form.userId" placeholder="请输入用户编号" @focus="handleOpenUserTable"/>
            </el-form-item> -->
            <el-row>
              <el-form-item label="所属客户" prop="tenantId">
                <el-select filterable v-model="form.tenantId" placeholder="请选择所属客户" style="width: 202px;">
                  <el-option
                    v-for="dept in deptOption"
                    :key="dept.tenantId"
                    :label="dept.deptName"
                    :value="dept.tenantId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="区域名称" prop="sheetsCode">
                <treeselect v-model="form.sheetsCode" :options="sheetsTreeList" :normalizer="normalizer"
                            :show-count="true"
                            placeholder="请选择区域名称"
                            @select="handleSheetsChange"
                            :disable-branch-nodes="true"
                            style="width:202px;">
                  <template v-slot:option-label="{ node, shouldShowCount, count }">
                  <span>
                    <!-- 这里添加你的图标，可以是字体图标或图片 -->
                    <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="node.raw.deviceType === 0"></span>
                    <span class="iconfont icon-loudong icon-padding" v-if="node.raw.deviceType === 1"></span>
                    <span class="iconfont icon-a-homezhuyefangzijia icon-padding"
                          v-if="node.raw.deviceType === 2"></span>
                    {{ node.label }}
                    <!-- 如果需要，可以显示选中的数量 -->
                    <span v-if="shouldShowCount">({{ count }})</span>
                  </span>
                  </template>
                </treeselect>
              </el-form-item>
              <el-form-item>
                <el-tooltip class="item" effect="dark" content="如果区域为灰，需要现在区域下添加楼栋" placement="bottom">
                  <span class="iconfont icon-wenhao" style="color: #1890ff; font-size: 18px;"></span>
                </el-tooltip>
              </el-form-item>
            </el-row>
            <el-form-item label="协议" prop="protocolId">
              <el-select v-model="form.protocolId" placeholder="请选择协议" style="width: 202px;">
                <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId"
                           :label="protocolItem.protocolName" :value="protocolItem.protocolId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表解析地址" prop="communicateAddress">
              <el-input v-model="form.communicateAddress" placeholder="请输入表解析地址"/>
            </el-form-item>
            <el-form-item label="是否带阀控" prop="valveControl">
              <el-select v-model="form.valveControl" placeholder="请选择是否带阀控" style="width: 202px;">
                <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="阀门地址" prop="valveAddress">
              <el-input v-model="form.valveAddress" placeholder="请输入阀门地址"/>
            </el-form-item>
            <el-form-item label="抄表周期" prop="meterReaderCycle">
              <el-select v-model="form.meterReaderCycle" placeholder="请选择抄表周期" style="width: 202px;">
                <el-option label="12小时" :value="12"></el-option>
                <el-option label="24小时" :value="24"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="安装日期" prop="installDate">
              <el-date-picker clearable
                              v-model="form.installDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择安装日期"
                              style="width: 202px;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="安装地址" prop="installAddress">
              <el-input v-model="form.installAddress" placeholder="请输入安装地址"/>
            </el-form-item>
            <el-form-item label="AEP平台的唯一码" prop="deviceId" v-if="title === '修改已绑定户表档案'">
              <el-input v-model="form.deviceId" placeholder="请输入AEP平台的唯一码"/>
            </el-form-item>
            <el-form-item label="注册平台" prop="signPlatform">
              <el-select v-model="form.signPlatform" placeholder="请选择注册平台" style="width: 202px;" clearable @change="handleSignPlatFormChange">
                <el-option v-for="dict in dict.type.sign_platform" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="通讯类型" prop="communicationType" v-if="showCommunicationType">
              <el-select v-model="form.communicationType" placeholder="请选择通讯类型" style="width: 202px;">
                <el-option v-for="dict in dict.type.communication_type" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="集中器" prop="concentratorId">
              <el-select filterable v-model="form.concentratorId" placeholder="请选择集中器" style="width: 202px;" clearable @change="handleConcentratorChange">
                <el-option v-for="item of concentratorOption" :key="item.id" :label="item.concentratorName"
                           :value="parseInt(item.id)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采集器" prop="collectorId">
              <el-select filterable v-model="form.collectorId" placeholder="请选择采集器" style="width: 202px;" clearable>
                <el-option v-for="item of collectorList" :key="item.id" :label="item.collectorName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="IMSI" prop="imsi">
              <el-input v-model="form.imsi" placeholder="当平台为OneNET时填写"/>
            </el-form-item>

            <el-form-item label="设备口径" prop="terminalCalibre">
              <el-select v-model="form.terminalCalibre" placeholder="请选择口径" style="width: 202px;">
                <el-option v-for="dict in dict.type.ldbd_pipe_caliber" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
            <!-- <el-form-item label="能耗分项" prop="energyUseItem">
              <el-select v-model="form.energyUseItem" placeholder="请选择能耗分项" style="width: 202px;">
                <el-option v-for="dict in dict.type.energy_use_item" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item> -->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 换表对话框 -->
        <el-dialog :title="title" :visible.sync="openReplace" width="740px" append-to-body>
          <el-form ref="replaceMeteredForm" :model="replaceMeteredForm" :rules="replaceMeteredRules" label-width="130px" :inline="true">
            <el-form-item label="旧设备编号" prop="terminalId">
              <el-input v-model="replaceMeteredForm.terminalId" placeholder="请输入旧设备编号" :disabled="true"/>
            </el-form-item>
            <el-form-item label="新设备编号" prop="newTerminalId">
              <el-input v-model="replaceMeteredForm.newTerminalId" placeholder="请输入新设备编号"/>
            </el-form-item>
            <el-form-item label="厂家名称" prop="supplierId">
              <el-select v-model="replaceMeteredForm.supplierId" filterable placeholder="请输入厂家名称" style="width: 202px;">
                <el-option
                  v-for="dict in dict.type.terminal_supplier"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表型号" prop="typeId">
              <el-select v-model="replaceMeteredForm.typeId" filterable placeholder="请选择表型号" clearable style="width: 202px;">
                <el-option
                  v-for="dict in dict.type.module_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="旧IMEI" prop="imei">
              <el-input v-model="replaceMeteredForm.imei" placeholder="请输入旧IMEI" :disabled="true"/>
            </el-form-item>
            <el-form-item label="新IMEI" prop="newImei">
              <el-input v-model="replaceMeteredForm.newImei" placeholder="请输入新IMEI"/>
            </el-form-item>
            <el-form-item label="旧表底数" prop="baseReading">
              <el-input v-model="replaceMeteredForm.baseReading" placeholder="请输入表底数" :disabled="true"/>
            </el-form-item>
            <el-form-item label="新表底数" prop="newBaseReading">
              <el-input v-model="replaceMeteredForm.newBaseReading" placeholder="请输入表底数"/>
            </el-form-item>
            <!-- <el-form-item label="用户编号" prop="userId"> -->
<!--              <el-select v-model="replaceMeteredForm.userId" filterable style="width: 202px;">-->
<!--                <el-option v-for="user in usersXbList" :key="user.userId" :value="user.userId"-->
<!--                           :label=" user.userId + '：' + user.userName ">-->
<!--                </el-option>-->
<!--              </el-select>-->
              <!-- <el-input v-model="replaceMeteredForm.userId" :disabled="true" placeholder="请输入用户编号" @focus="handleOpenUserTable"/> -->
            <!-- </el-form-item> -->
            <el-form-item label="设备口径" prop="terminalCalibre">
              <el-select v-model="replaceMeteredForm.terminalCalibre" placeholder="请选择口径" style="width: 202px;">
                <el-option v-for="dict in dict.type.ldbd_pipe_caliber" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item label="所属客户" prop="tenantId">
                <el-select filterable v-model="replaceMeteredForm.tenantId" placeholder="请选择所属客户" style="width: 202px;">
                  <el-option
                    v-for="dept in deptOption"
                    :key="dept.tenantId"
                    :label="dept.deptName"
                    :value="dept.tenantId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="区域名称" prop="sheetsCode">
                <treeselect v-model="replaceMeteredForm.sheetsCode" :options="sheetsTreeList" :normalizer="normalizer"
                            :show-count="true"
                            placeholder="请选择区域名称"
                            @select="handleSheetsChange"
                            :disable-branch-nodes="true"
                            style="width:202px;">
                  <template v-slot:option-label="{ node, shouldShowCount, count }">
                  <span>
                    <!-- 这里添加你的图标，可以是字体图标或图片 -->
                    <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="node.raw.deviceType === 0"></span>
                    <span class="iconfont icon-loudong icon-padding" v-if="node.raw.deviceType === 1"></span>
                    <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="node.raw.deviceType === 2"></span>
                    {{ node.label}}
                    <!-- 如果需要，可以显示选中的数量 -->
                    <span v-if="shouldShowCount">({{ count }})</span>
                  </span>
                  </template>
                </treeselect>
              </el-form-item>
              <el-form-item>
                <el-tooltip class="item" effect="dark" content="如果区域为灰，需要现在区域下添加楼栋" placement="bottom">
                  <span class="iconfont icon-wenhao" style="color: #1890ff; font-size: 18px;"></span>
                </el-tooltip>
              </el-form-item>
            </el-row>
            <el-form-item label="协议" prop="protocolId">
              <el-select v-model="replaceMeteredForm.protocolId" placeholder="请选择协议" style="width: 202px;">
                <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId"
                           :label="protocolItem.protocolName" :value="protocolItem.protocolId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表解析地址" prop="communicateAddress">
              <el-input v-model="replaceMeteredForm.communicateAddress" placeholder="请输入表解析地址"/>
            </el-form-item>
            <el-form-item label="是否带阀控" prop="valveControl">
              <el-select v-model="replaceMeteredForm.valveControl" placeholder="请选择是否带阀控" style="width: 202px;">
                <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="阀门地址" prop="valveAddress">
              <el-input v-model="replaceMeteredForm.valveAddress" placeholder="请输入阀门地址"/>
            </el-form-item>
            <el-form-item label="抄表周期" prop="meterReaderCycle">
              <el-select v-model="replaceMeteredForm.meterReaderCycle" placeholder="请选择抄表周期" style="width: 202px;">
                <el-option label="12小时" :value="12"></el-option>
                <el-option label="24小时" :value="24"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="安装日期" prop="installDate">
              <el-date-picker clearable
                              v-model="replaceMeteredForm.installDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择安装日期"
                              style="width: 202px;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="安装地址" prop="installAddress">
              <el-input v-model="replaceMeteredForm.installAddress" placeholder="请输入安装地址"/>
            </el-form-item>
            <el-form-item label="AEP平台的唯一码" prop="deviceId" v-if="title === '修改已绑定户表档案'">
              <el-input v-model="replaceMeteredForm.deviceId" placeholder="请输入AEP平台的唯一码"/>
            </el-form-item>
            <el-form-item label="注册平台" prop="signPlatform">
              <el-select v-model="replaceMeteredForm.signPlatform" placeholder="请选择注册平台" style="width: 202px;">
                <el-option v-for="dict in dict.type.sign_platform" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="集中器" prop="concentratorId">
              <el-select v-model="replaceMeteredForm.concentratorId" placeholder="请选择集中器" style="width: 202px;" clearable>
                <el-option v-for="item of concentratorOption" :key="item.id" :label="item.concentratorName"
                           :value="parseInt(item.id)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="IMSI" prop="imsi">
              <el-input v-model="replaceMeteredForm.imsi" placeholder="当平台为OneNET时填写"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="replaceMeteredForm.remark" placeholder="请输入备注"/>
            </el-form-item>
            <el-form-item label="能耗分项" prop="energyUseItem">
              <el-select v-model="form.energyUseItem" placeholder="请选择能耗分项" style="width: 202px;">
                <el-option v-for="dict in dict.type.energy_use_item" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitReplaceMeteredForm">确 定</el-button>
            <el-button @click="cancelReplaceMetered">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
<!--              <div class="el-upload__tip" slot="tip">-->
<!--                <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
<!--              </div>-->
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 远程控制对话框 -->
        <el-dialog :title="title" :visible.sync="openReomteControl" width="700px" append-to-body
                   @close="closeReomoteDialog">
          <el-form ref="reomtecontrolform" :model="reomteControlForm" :rules="remoteControlRules"
                   :label-width="labelWidth"
                   :inline="true">
            <el-form-item label="命令类型" prop="commandType">
              <el-select v-model="reomteControlForm.commandType" filterable placeholder="请选择命令类型"
                         style="width: 202px;">
                <el-option
                  v-for="dict in dict.type.command_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="isOpen">
              <el-radio-group v-model="reomteControlForm.isOpen">
                <el-radio label="1">开</el-radio>
                <el-radio label="2">关</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <!-- 提示信息 -->
          <el-alert
            :title="alert.alertContent"
            :type="alert.alertType"
            :closable="false"
            v-if="alert.alertContent != null && alert.alertContent != ''">
          </el-alert>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="sendForm" :disabled="submitdisabled">发送</el-button>
          </div>
        </el-dialog>
        <RegisterDialog :dialogTitle="register.title" :dialogVisible="register.open" @isClose="isClose"
                        @getList="getList"></RegisterDialog>
<!--        用户信息对话框-->
        <el-dialog :title="userTitle" :visible.sync="openUserTabel" width="840px" append-to-body @close="handleUserClose">
          <el-row>
            <el-col :span="19">
              <el-form :model="queryParamsUser" ref="queryFormUser" :size="formItemSize" :label-width="labelWidth">
                <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                  <el-form-item label="用户名称" prop="userName">
                    <el-input
                      v-model="queryParamsUser.userName"
                      placeholder="请输入用户名称"
                      clearable
                      @keyup.enter.native="handleQuery"
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="用户编号" prop="userId">
                    <el-input
                      v-model="queryParamsUser.userId"
                      placeholder="请输入用户编号"
                      clearable
                      @keyup.enter.native="handleQuery"
                      style="width: 130px"
                    />
                  </el-form-item>
                  <el-form-item label="所属客户" prop="tenantId" v-if="systemFlag !== 2">
                    <el-select filterable clearable v-model="queryParamsUser.tenantId" placeholder="请选择所属客户" style="width: 130px">
                      <el-option
                        v-for="dept in deptOption"
                        :key="dept.tenantId"
                        :label="dept.deptName"
                        :value="dept.tenantId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-form>
            </el-col>
            <el-col :span="5">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
            </el-col>
          </el-row>
          <el-table v-loading="userTableloading" :data="usersXbList" size="mini" row-key="id" border height="390px" ref="userTable"
                    @selection-change="handleUserSelectionChange" @select="selectUser" :default-sort="defaultSort" @sort-change="handleUserSorterChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="用户编号" align="center" prop="userId"
                             :show-overflow-tooltip="true" sortable="custom"
                             :sort-orders="['ascending', 'descending']"/>
            <el-table-column label="用户名称" align="center" prop="userName"
                             :show-overflow-tooltip="true" sortable="custom"
                             :sort-orders="['ascending', 'descending']"/>
            <el-table-column label="所属客户" align="center" prop="deptName"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="用户状态" align="center" prop="userMark"
                             :show-overflow-tooltip="true" sortable="custom"
                             :sort-orders="['ascending', 'descending']">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.user_status" :value="scope.row.userMark"/>
              </template>
            </el-table-column>
            <el-table-column label="立户时间" align="center" prop="createTime"
                             :show-overflow-tooltip="true" sortable="custom"
                             :sort-orders="['ascending', 'descending']">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="usertotal>0"
            :total="usertotal"
            :page.sync="queryParamsUser.pageNum"
            :limit.sync="queryParamsUser.pageSize"
            @pagination="getUserList"
          />
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleUserOk">确 定</el-button>
            <el-button @click="handleUserCancel">取 消</el-button>
          </div>
        </el-dialog>
<!--        表过户对话框-->
        <el-dialog :title="title" :visible.sync="openTransferUser" width="840px" @close="handleTransferUserClose">
          <el-form ref="changeUserform" :model="changeUserForm" :rules="changeUserRules" label-width="150px" :inline="true">
            <el-form-item label="设备编号" prop="terminalId" key="terminalId">
              <el-input v-model="changeUserForm.terminalId" placeholder="请输入设备编号" :disabled="true"/>
            </el-form-item>
<!--            <el-form-item label="新设备编号" prop="terminalId">-->
<!--              <el-input v-model="changeUserForm.terminalId" placeholder="请输入新设备编号"/>-->
<!--            </el-form-item>-->
              <el-form-item label="是否新建用户" prop="newUser" key="newUser">
                <el-radio-group v-model="changeUserForm.newUser" @change="handleCreateUser" style="width: 202px;">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            <el-form-item label="表型号" prop="typeId" key="typeId">
              <el-select :disabled="true" v-model="changeUserForm.typeId" filterable placeholder="请选择表型号" clearable style="width: 202px;">
                <el-option
                  v-for="dict in dict.type.module_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表底数" prop="baseReading" key="baseReading">
              <el-input :disabled="true" v-model="changeUserForm.baseReading" placeholder="请输入表底数"/>
            </el-form-item>
            <el-form-item label="设备口径" prop="terminalCalibre" key="terminalCalibre">
              <el-select :disabled="true" v-model="changeUserForm.terminalCalibre" placeholder="请选择口径" style="width: 202px;">
                <el-option v-for="dict in dict.type.ldbd_pipe_caliber" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="旧用户编号" prop="oldUserId" key="oldUserId">
              <el-input v-model="changeUserForm.oldUserId" placeholder="请输入旧用户编号" :disabled="true"/>
            </el-form-item>
            <el-row>
              <el-form-item label="旧用户名称" prop="oldUserName" key="oldUserName">
                <el-input v-model="changeUserForm.oldUserName" placeholder="请输入旧用户名称" :disabled="true"/>
              </el-form-item>
              <el-form-item label="新用户编号"  prop="userId" key="userId" v-if="changeUserForm.newUser === false">
                <el-input v-model="changeUserForm.userId"  placeholder="请输入新用户编号"/>
              </el-form-item>
              <el-form-item v-if="changeUserForm.newUser === false">
                <el-tooltip class="item" effect="dark" content="点击此按钮选择用户" placement="top-start">
                  <i class="el-icon-user-solid" style="color: #1890ff" @click="handleOpenUserTable" ></i>
                </el-tooltip>
              </el-form-item>
            </el-row>
            <el-form-item label="新用户编号" prop="userId" key="userId" v-if="changeUserForm.newUser === true">
              <el-input v-model="changeUserForm.userId" placeholder="请输入新用户编号"/>
            </el-form-item>
            <el-form-item label="新用户名称" prop="userName" key="userName" v-if="changeUserForm.newUser === true">
              <el-input v-model="changeUserForm.userName" :disabled="!changeUserForm.newUser" placeholder="请输入新用户名称"/>
            </el-form-item>
            <el-form-item label="新用户联系方式" prop="userPhone" key="userPhone" v-if="changeUserForm.newUser === true">
              <el-input v-model="changeUserForm.userPhone" placeholder="请输入用户联系方式"/>
            </el-form-item>
            <el-form-item label="新用户证件类型" prop="idType" key="idType" v-if="changeUserForm.newUser === true">
              <el-input v-model="changeUserForm.idType" placeholder="请输入新用户证件类型"/>
            </el-form-item>
            <el-form-item label="新用户证件号码" prop="userCode" key="userCode" v-if="changeUserForm.newUser === true">
              <el-input v-model="changeUserForm.userCode" placeholder="请输入新用户证件号码"/>
            </el-form-item>
            <el-form-item label="新用户通讯地址" prop="userAddress" key="userAddress" v-if="changeUserForm.newUser === true">
              <el-input v-model="changeUserForm.userAddress" placeholder="请输入新用户通讯地址"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitTransferUserForm">确 定</el-button>
            <el-button @click="cancelTransferUserForm">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { gcj2bdString } from "@/utils/coordinate";
import { listConcentrator } from "@/api/record/concentrator";
import {
  listCollector,
} from "@/api/record/collector";
import {getAreaTree} from "@/api/tree/index"
import {Message} from 'element-ui'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import moment from 'moment'
import {
  listTerminalxb,
  getTerminalxb,
  delTerminalxb,
  addTerminalxb,
  updateTerminalxb,
  cancelterminal,
  remoteControl,
  changeTerminalXb,
  changeTerminalUser
} from "@/api/record/terminalxb";
import {selectProtocol} from '@/api/basedata/protocol.js'
import {getToken} from "@/utils/auth";
import RegisterDialog from '../../record/metered/component/registerDialog.vue'
import {concentratorOption} from '@/api/record/concentrator'
import RealTime from './components/RealTime.vue'
import Dosage from './components/Dosage.vue'
import Log from './components/Log.vue'
import Alarm from './components/Alarm.vue'
import History from './components/History.vue'
import {listMeterSheetsTree} from "@/api/basedata/meterSheets";
import {listUsersxb} from "@/api/record/usersxb";
import {deptList} from '@/api/system/dept.js'
import {getByLocationNb} from "../../../api/record/terminalxb";

export default {
  name: "Meter",
  components: {Treeselect, RegisterDialog, RealTime, Dosage, Log, Alarm, History},
  dicts: ['energy_use_item','communication_type','user_status','yes_no', 'used_status', 'belong_department', 'module_type', 'command_type', 'terminal_supplier', 'reader_cycle', 'sign_platform', 'ldbd_pipe_caliber', 'ldbd_pipe_caliber', 'bind_status'],
  data() {
    return {
      // 定位弹窗参数
      mapdialog: {
        title: '定位',
        open: false,
      },
      ids: [],
      // 用户表勾选的数据
      userSelectData: {},
      // 默认展开的树节点
      defaultExpandedKeys: [],
      treeWidth: '',
      screenHeight: null,
      // 遮罩层
      loading: true,
      userTableloading: true,
      // 显示搜索条件
      showSearch: true,
      // 区域树选项
      sheetsTreeList: [],
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      filterText: '',
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      usertotal: 0,
      // 区域管理表格数据
      terminalxbList: [],
      // 弹出层标题
      title: "",
      userTitle: "",
      // 是否显示弹出层
      open: false,
      openReomteControl: false,
      openReplace: false,
      openUserTabel: false,
      openTransferUser: false,
      submitdisabled: false,
      treeLoading: false,
      // 用户选项
      usersXbList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: null,
        userName: null,
        userId: null,
        terminalId: null,
        loginUserId: null,
        systemFlag: null,
        isBound: null,
        tenantId: null,
        signPlatform: null,
        communicationType: null,
        terminalMark: null,
      },
      queryParamsUser: {
        pageNum: 1,
        pageSize: 20,
        userName: null,
        userId: null,
        tenantId: null,
        userMark: 1,
        // unbound: null,
        energyType:2,
      },
      // 列信息
      columns: [
        {key: 0, label: `用户名称`, visible: true},
        {key: 1, label: `用户编号`, visible: true},
        {key: 2, label: `设备编号`, visible: true},
        {key: 3, label: `IMEI`, visible: true},
        {key: 4, label: `厂家名称`, visible: true},
        {key: 5, label: `表型号`, visible: true},
        {key: 6, label: `表底数`, visible: true},
        {key: 7, label: `是否带阀控`, visible: true},
        {key: 8, label: `阀门地址`, visible: true},
        {key: 9, label: `安装日期`, visible: true},
        {key: 10, label: `抄表周期`, visible: true},
        {key: 11, label: `表状态`, visible: true},
        {key: 12, label: `协议名称`, visible: true},
        {key: 13, label: `表解析地址`, visible: true},
        {key: 14, label: `集中器`, visible: true},
        {key: 15, label: `所属客户`, visible: false},
        {key: 16, label: `通讯类型`, visible: true},
        // {key: 17, label: `注册平台`, visible: false}
        {key: 17, label: `设备名称`, visible: true},
          {key: 18, label: `区域名称`, visible: true},
      ],
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
      // 表单参数
      form: {},
      replaceMeteredForm: {},
      changeUserForm: {},
      // 远程控制提示信息
      alert: {
        alertContent: null,
        alertType: 'success'
      },
      // 客户下拉框中的数据
      deptOption: [],
      // 协议下拉框中的数据
      protocolOption: [],
      // 集中器下拉框
      concentratorOption: [],
      // 采集器下拉框
      collectorList: [],
      nobindform: {},
      // 远程控制表单
      reomteControlForm: {
        commandType: "0",
        isOpen: '1'
      },
      register: {
        title: 'NB平台注册',
        open: false,
      },
      registerform: {
        IMEI: '',
        IMSI: ''
      },
      // 表单校验
      rules: {
        terminalId: [
          {required: true, message: "设备编号不能为空", trigger: "blur"}
        ],
        supplierId: [
          {required: true, message: "厂家名称不能为空", trigger: "change"}
        ],
        tenantId: [
          {required: true, message: "请选择所属客户", trigger: "change"}
        ],
        parentId: [
          {required: true, message: "请选择父级区域", trigger: "blur"}
        ],
        sheetsName: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        sheetsCode: [
          {required: true, message: "区域编号不能为空", trigger: "blur"}
        ],
        protocolId: [
          {required: true, message: "协议名称不能为空", trigger: "change"}
        ],
        communicateAddress: [
          {required: true, message: "表解析地址不能为空", trigger: "blur"}
        ],
        imei: [
          {required: true, message: "IMEI不能为空", trigger: "blur"}
        ],
        signPlatform: [
          {required: true, message: "注册平台不能为空", trigger: "change"}
        ],
        meterReaderCycle: [
          {required: true, message: "抄表周期不能为空", trigger: "change"}
        ],
        communicationType: [
          {required: true, message: "通讯类型不能为空", trigger: "change"}
        ]
      },
      changeUserRules: {
        // terminalId: [
        //   {required: true, message: "新设备编号不能为空", trigger: "blur"}
        // ],
        userId: [
          {required: true, message: "新用户编号不能为空", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "新用户名称不能为空", trigger: "blur"}
        ],
      },
      replaceMeteredRules: {
        terminalId: [
          {required: true, message: "旧设备编号不能为空", trigger: "blur"}
        ],
        newTerminalId: [
          {required: true, message: "新设备编号不能为空", trigger: "blur"}
        ],
        supplierId: [
          {required: true, message: "厂家名称不能为空", trigger: "change"}
        ],
        tenantId: [
          {required: true, message: "请选择所属客户", trigger: "change"}
        ],
        parentId: [
          {required: true, message: "请选择父级区域", trigger: "blur"}
        ],
        sheetsName: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        sheetsCode: [
          {required: true, message: "区域编号不能为空", trigger: "blur"}
        ],
        protocolId: [
          {required: true, message: "协议名称不能为空", trigger: "change"}
        ],
        communicateAddress: [
          {required: true, message: "表解析地址不能为空", trigger: "blur"}
        ],
        imei: [
          {required: true, message: "旧IMEI不能为空", trigger: "blur"}
        ],
        newImei: [
          {required: true, message: "新IMEI不能为空", trigger: "blur"}
        ],
        signPlatform: [
          {required: true, message: "注册平台不能为空", trigger: "change"}
        ],
        meterReaderCycle: [
          {required: true, message: "抄表周期不能为空", trigger: "change"}
        ]
      },
      remoteControlRules: {
        commandType: [
          {required: true, message: "请选择命令类型", trigger: "change"}
        ],
        isOpen: [
          {required: true, message: "请选择状态", trigger: "change"}
        ],
      },
      // 判断是否展示通讯类型表单
      showCommunicationType: false,
      maxShow: 4,
      formItemSize: 'mini',
      collapseAble: false,
      fold: false,
      labelWidth: '80px',
      uploadVisible: true,
      currentTerminalId: null,
      currentLocationNb: null,
      detailVisible: false,
      tabActiveKey: '1',
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/terminalxb/importData"
      },
      // 集中器数组
      concentratorList: [],
      concentratorIds: ''
    };
  },
  created() {
    this.getTreeList();
    this.getDeptList();
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? (this.fold ? 295 : 255) : 195)
    },
    loginUserId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    },
    name() {
      return this.$store.state.user.name
    },
  },
  methods: {
    handleSignPlatFormChange(e) {
      if(e === 3){
        this.showCommunicationType = true
      }else {
        this.showCommunicationType = false
      }
    },
    // 是否创建用户 单选事件
    handleCreateUser(e) {
      this.changeUserForm = {
        // oldTerminalId: this.changeUserForm.oldTerminalId,
        oldUserId: this.changeUserForm.oldUserId,
        oldUserName: this.changeUserForm.oldUserName,
        typeId: this.changeUserForm.typeId,
        baseReading: this.changeUserForm.baseReading,
        terminalCalibre: this.changeUserForm.terminalCalibre,
        terminalId: this.changeUserForm.terminalId,
        userId: null,
        userName: null,
        userPhone: null,
        idType: null,
        userCode: null,
        userAddress: null,
        remark: null,
        newUser: e,
      }
    },
    // 点击表过户按钮
    handleTransferUser(row) {
      this.resetChangeUserForm();
      this.title = "表过户";
      const id = row.id
      getTerminalxb(id).then(response => {
        this.changeUserForm = {
          terminalId: response.data.terminalId,
          oldUserId: response.data.userId,
          userId: null,
          oldUserName: response.data.userName,
          userName: null,
          userPhone: null,
          idType: null,
          userCode: null,
          userAddress: null,
          remark: null,
          typeId: response.data.typeId,
          baseReading: response.data.baseReading,
          terminalCalibre: response.data.terminalCalibre,
          newUser: false,
        }
        this.openTransferUser = true;
      });
    },
    // 表过户提交按钮
    submitTransferUserForm() {
      // this.queryParamsUser= {
      //   pageNum: 1,
      //   pageSize: 20,
      //   userId: this.changeUserForm.userId,
      // }
      // listUsersxb(this.queryParamsUser).then(response => {
      //   if(response.rows.length > 0){
      //     this.changeUserForm.userId = response.rows[0].userId,
      //     this.changeUserForm.userName = response.rows[0].userName,
      //     this.changeUserForm.userPhone= response.rows[0].userPhone,
      //     this.changeUserForm.idType= response.rows[0].idType,
      //     this.changeUserForm.userCode= response.rows[0].userCode,
      //     this.changeUserForm.userAddress= response.rows[0].userAddress,
      //     this.changeUserForm.remark= response.rows[0].remark
      //   }else{
      //     this.changeUserForm.userId = ''
      //   }
      // });
      this.$refs["changeUserform"].validate(valid => {
        if (valid) {
          let form = {
            userId: this.changeUserForm.userId,
            userName: this.changeUserForm.userName,
            userPhone: this.changeUserForm.userPhone,
            idType: this.changeUserForm.idType,
            userCode: this.changeUserForm.userCode,
            userAddress: this.changeUserForm.userAddress,
            remark: this.changeUserForm.remark,
          }
          changeTerminalUser(form, this.changeUserForm.terminalId, this.changeUserForm.newUser).then(response => {
            if(response.code === 200){
              this.$modal.msgSuccess("表过户成功");
              this.openTransferUser = false;
              this.getList();
            }
          });
        }
      });
    },
    // 获取所有集中器
    async getConcentrator(pageNum, pageSize) {
      await listConcentrator({pageNum: pageNum, pageSize: pageSize}).then(response => {
        this.concentratorList = [...this.concentratorList, ...response.rows];
        if((response?.total) >= (pageSize * pageNum)) {
          this.getConcentrator(pageNum + 1, pageSize)
        }
      })
      this.concentratorIds = this.concentratorList.map(item => item.id).toString()
    },
    // 集中器下拉框改变事件
    handleConcentratorChange(e) {
      if(e === '' || e === null) {
        this.getConcentrator()
        this.getCollector(1, 100, this.concentratorIds)
      }else{
        // listCollector({concentratorIds: e}).then(response => {
        //   this.collectorList = response.rows
        // })
        this.getCollector(1, 100, e)
      }
    },
    // 获取采集器
    getCollectorData(pageNum, pageSize, concentratorIds) {
      listCollector({pageNum: pageNum, pageSize: pageSize, concentratorIds: concentratorIds}).then(response => {
        this.collectorList = [...this.collectorList, ...response.rows]
        if((response?.total) >= (pageSize * pageNum)) {
          this.getCollectorData(pageNum + 1, pageSize, concentratorIds)
        }
      })
    },
    // 获取所有采集器
    getCollector(pageNum, pageSize, concentratorIds) {
      this.collectorList = []
      this.getCollectorData(pageNum, pageSize, concentratorIds)
      // listConcentrator({pageNum: 1, pageSize: 1000}).then(response => {
      //   let concentratorList = response.rows;
      //   let collectorParams = {
      //     concentratorIds: concentratorList.map(item => item.id).toString()
      //   }
      //   listCollector(collectorParams).then(response => {
      //     this.collectorList = response.rows
      //   })
      // })
    },
    // 获取所有客户
    getDeptList() {
      deptList().then(response => {
        this.deptOption = response.data
      })
    },
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    // 用户表格排序
    handleUserSorterChange({column, prop, order}){
      this.queryParamsUser.orderByColumn = prop
      this.queryParamsUser.isAsc = order
      this.getUserList()
    },
    // 表过户取消按钮
    cancelTransferUserForm() {
      this.handleTransferUserClose()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: '' + node.sheetsCode,
        label: node.sheetsName,
        children: node.children,
        isDisabled: node.isDisabled
      };
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0){
        this.treeLoading = false;
      }else{
        this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
        this.sheetsTreeList.map(item => {
          this.getLeafKeys(item)
        })
        this.treeLoading = false;
      }

      // let treeType = "0,1"
      // getAreaTree(treeType).then(response => {
      //   this.sheetsTreeList = response.data;
      //   this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
      //   this.sheetsTreeList.map(item => {
      //     this.getLeafKeys(item)
      //   })
      //   this.treeLoading = false;
      // });
    },
    getLeafKeys(node) {
      //判断是否要禁用的条件
      if (node.deviceType === 0 && node.children.length === 0) {
        node.isDisabled = true
      } else {
        node.isDisabled = false
      }
      node.children.forEach(item => this.getLeafKeys(item))
    },
    // 区域下拉框改变触发事件
    handleSheetsChange(node) {
      this.form.sheetsId = node.id
    },
    /** 查询用户下拉框 */
    getUserList() {
      this.userTableloading = true
      // if(this.title === '表过户'){
      //   this.queryParamsUser.unbound = true
      // }else {
      //   this.queryParamsUser.unbound = null
      // }
      listUsersxb(this.queryParamsUser).then(response => {
        this.usersXbList = response.rows;
        this.usertotal = response.total;
        this.userTableloading = false
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    // 获取集中器下拉框中的数据
    getConcentratorOption() {
      concentratorOption().then(response => {
        // console.log(response,"response")
        this.concentratorOption = response.rows
      })
    },
    // 关闭远程控制对话框
    closeReomoteDialog() {
      this.$refs.reomtecontrolform.resetFields()
      this.submitdisabled = false
    },
    // 打开注册对话框
    handleRegister() {
      this.register.open = true
      // this.registerform.IMEI = ''
      this.register.title = 'NB平台注册'
    },
    // 关闭注册弹框
    isClose(val) {
      this.register.open = !val
    },
    // 判断表的状态禁用表格多选按钮
    selectable(row, rowIndex) {
      if (row.terminalMark === 1) {
        return true;  //不禁用
      } else {
        return false;  //禁用
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "户表档案导入";
      this.upload.open = true;
      this.upload.url = process.env.VUE_APP_BASE_API + "/basedata/terminalxb/importData"
    },
    // 批量更新按钮
    handleBatchUpdate() {
      this.upload.title = "户表档案批量更新";
      this.upload.open = true;
      this.upload.url = process.env.VUE_APP_BASE_API + "/basedata/terminalxb/batchUpdate"
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if(this.upload.title === '户表档案导入'){
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      }else if(this.upload.title === '户表档案批量更新') {
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "更新结果", {dangerouslyUseHTMLString: true});
      }
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 获取协议下拉框中的数据
    getSelectProtocol() {
      let TerminalType = 2
      selectProtocol(TerminalType).then(response => {
        this.protocolOption = response.data
      })
    },
    /** 查询已绑定小档案列表 */
    getList() {
      this.checkSortColumn()
      this.loading = true;
      let choiceCheck = this.$refs.tree.getCurrentNode();
      if (choiceCheck !== null) {
        this.queryParams.sheetsCode = choiceCheck.sheetsCode
      } else {
        this.queryParams.sheetsCode = null
      }
      this.queryParams.systemFlag = this.systemFlag
      this.queryParams.loginUserId = this.loginUserId
      listTerminalxb(this.queryParams).then(response => {
        this.terminalxbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleUserCancel() {
      this.openUserTabel = false
      this.resetForm('queryFormUser')
    },
    // 表单重置
    reset() {
      this.form = {
        terminalId: null,
        imei: null,
        supplierId: null,
        typeId: null,
        baseReading: null,
        userId: null,
        tenantId: null,
        sheetsCode: null,
        protocolId: null,
        communicateAddress: null,
        valveControl: null,
        valveAddress: null,
        meterReaderCycle: null,
        installDate: null,
        installAddress: null,
        deviceId: null,
        signPlatform: null,
        communicationType: null,
        concentratorId: null,
        collectorId: null,
        imsi: null,
        terminalCalibre: null,
        remark: null,
      };
      this.resetForm("formXb");
    },
    resetReplaceMetered(){
      this.resetForm('replaceMeteredForm')
    },
    // 远程控制表单重置
    resetReomteControl() {
      this.reomteControlForm = {
        commandType: "0",
        isOpen: '1'
      }
    },
    /** 修改户表档案按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.showCommunicationType = false
      const id = row.id || this.ids
      getTerminalxb(id).then(response => {
        this.form = response.data;
        if(this.form.signPlatform === 3) {
          this.showCommunicationType = true
        }
        this.open = true;
        this.title = "修改户表档案";
      });
    },
    // 远程控制发送
    sendForm() {
      this.$refs["reomtecontrolform"].validate(valid => {
        if (valid) {
          let form = this.terminalInfoObj
          form.commandType = this.reomteControlForm.commandType
          form.isOpen = this.reomteControlForm.isOpen
          remoteControl(form).then(response => {
            this.alert.alertContent = moment(new Date()).format("YYYY-MM-DD HH:mm:ss") + ":" + response.msg
            if (response.code == 200) {
              this.alert.alertType = 'success'
            } else {
              this.alert.alertType = "error"
            }
          })
        }
      })
    },
    /** 已绑定提交按钮 */
    submitForm() {
      this.$refs["formXb"].validate(valid => {
        if (valid) {
          if (this.title === "修改户表档案") {
            updateTerminalxb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else if (this.title === "添加户表档案") {
            addTerminalxb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 用户信息弹窗确认
    handleUserOk(){
      if(this.title === '添加户表档案' || this.title === '修改户表档案'){
        this.form.userId = this.userSelectData.userId
      }else if(this.title === '换表'){
        this.replaceMeteredForm.userId = this.userSelectData.userId
      }else if(this.title === '表过户'){
        this.changeUserForm.userId = this.userSelectData.userId
        this.changeUserForm.userName = this.userSelectData.userName
        this.changeUserForm.userPhone = this.userSelectData.userPhone
        this.changeUserForm.idType = this.userSelectData.idType
        this.changeUserForm.userCode = this.userSelectData.userCode
        this.changeUserForm.userAddress = this.userSelectData.userAddress
        this.changeUserForm.remark = this.userSelectData.remark
      }
      this.openUserTabel = false
    },
    handleOpenValve(row) {
      this.$modal.confirm('是否确认开启该表阀门？').then(function () {
        let form = Object.assign({}, row)
        form.commandType = '0'
        form.isOpen = '1'
        remoteControl(form).then(response => {
          if (response.code === 200) {
            Message.success(response.msg)
          } else {
            Message.error(response.msg)
          }
        })
      })
    },
    handleCloseValve(row) {
      this.$modal.confirm('是否确认关闭该表阀门？').then(function () {
        let form = Object.assign({}, row)
        form.commandType = '0'
        form.isOpen = '2'
        remoteControl(form).then(response => {
          if (response.code === 200) {
            Message.success(response.msg)
          } else {
            Message.error(response.msg)
          }
        })
      })
    },
    // 打开用户表格弹窗
    handleOpenUserTable(){
      this.userTitle="用户信息"
      this.openUserTabel = true
      this.getUserList()
    },
    // 关闭用户信息弹窗
    handleUserClose() {
      this.resetForm('queryFormUser')
      this.openUserTabel = false
    },
    // 表过户弹窗关闭事件
    handleTransferUserClose() {
      this.openTransferUser = false
    },
    /** 已绑定删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id || this.ids;
      const terminalIDs = row.terminalId || this.terminalids;
      this.$modal.confirm('是否确认删除户表档案编号为"' + terminalIDs + '"的数据项？').then(function () {
        return delTerminalxb(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/terminalxb/export', {
        ...this.queryParams
      }, `terminalxb_${new Date().getTime()}.xlsx`)
    },
    // 下载模板
    importTemplate(){
      if(this.upload.title === "户表档案导入"){
        this.download('basedata/terminalxb/getImportTemplate', {}, `户表档案模板_${new Date().getTime()}.xlsx`)
      }else if(this.upload.title === "户表档案批量更新"){
        this.download('basedata/terminalxb/getBatchUpdateTemplate', {}, `户表档案更新模板_${new Date().getTime()}.xlsx`)
      }
    },
    // 换表
    handleReplaceTerminal(row) {
      this.resetReplaceMetered();
      this.title = "换表";
      this.openReplace = true;
      const id = row.id
      getTerminalxb(id).then(response => {
        this.replaceMeteredForm = response.data;
        this.openReplace = true;
        this.title = "换表";
      });
    },
    submitReplaceMeteredForm(){
      this.$refs["replaceMeteredForm"].validate(valid => {
        if (valid) {
          changeTerminalXb(this.replaceMeteredForm).then(response => {
            if(response.code === 200){
              this.$modal.msgSuccess("换表成功");
              this.openReplace = false;
              this.getList();
            }
          });
        }
      });
    },
    // 取消换表
    cancelReplaceMetered() {
      this.openReplace = false;
      this.resetReplaceMetered();
    },
    // 销表
    handledeleteterminal(row) {
      this.reset()
      // 1使用中 0停用
      this.form = row
      if (row.terminalMark === 1) {
        this.$modal.confirm('是否确认停用编号为"' + row.terminalId + '"的表？').then(() => {
          return cancelterminal(this.form)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("销表成功!");

        }).catch(() => {
        });
      } else if (row.terminalMark === 0) {
        this.$modal.msgWarning("此表已停用！");
      }
    },
    handleNodeClick(data) {
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleUserQuery() {
      this.queryParamsUser.pageNum = 1;
      this.queryParamsUser.userMark = 1
      this.getUserList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery();
    },
    // 重置用户表格查询
    resetUserQuery() {
      this.resetForm("queryFormUser");
      this.handleUserQuery();
    },
    // 重置表过户表单
    resetChangeUserForm() {
      this.changeUserForm = {
        // oldTerminalId: null,
        terminalId: null,
        oldUserId: null,
        userId: null,
        oldUserName: null,
        userName: null,
        userPhone: null,
        idType: null,
        userCode: null,
        userAddress: null,
        remark: null,
        typeId: null,
        baseReading: null,
        terminalCalibre: null,
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.terminalids = selection.map(item => item.terminalId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 用户表格选择
    handleUserSelectionChange(val){
      this.userSelectData = val[0]
    },
    selectUser(selection, row){
      this.$refs.userTable.clearSelection();
      if(selection.length === 0){
        return
      }else{
        this.$refs.userTable.toggleRowSelection(row, true)
      }
    },
     /** 添加户表档案按钮操作 */
    handleAdd() {
      this.reset();
      this.showCommunicationType = false
      this.title = "添加户表档案";
      this.open = true;
    },
    handleDetail(row) {
      this.currentTerminalId = row.terminalId
      this.currentLocationNb = row.locationNb
      this.detailVisible = true
      this.$nextTick(() => {
        this.doLoadTabPaneData(this.tabActiveKey)
      })
    },
    handleDetailClose() {
      this.currentTerminalId = null
      this.currentLocationNb = null
      this.tabActiveKey = '1'
    },
    handleTabClick(tab) {
      this.doLoadTabPaneData(tab._props.name)
    },
    doLoadTabPaneData(tabName) {
      this.$nextTick(() => {
        if (tabName === '1') {
          this.$refs.refMeterRealTime.updateTerminalId(this.currentTerminalId, this.currentLocationNb)
          this.$refs.refMeterRealTime.loadData()
        } else if (tabName === '2') {
          this.$refs.refMeterDosage.updateTerminalId(this.currentTerminalId, this.currentLocationNb)
          this.$refs.refMeterDosage.getList()
        } else if (tabName === '3') {
          this.$refs.refMeterHistory.updateTerminalId(this.currentTerminalId, this.currentLocationNb)
          this.$refs.refMeterHistory.getList()
        } else if (tabName === '4') {
          this.$refs.refMeterLog.updateTerminalId(this.currentTerminalId, this.currentLocationNb)
          this.$refs.refMeterLog.getList()
        } else {
          this.$refs.refMeterAlarm.updateTerminalId(this.currentTerminalId, this.currentLocationNb)
          this.$refs.refMeterAlarm.getList()
        }
      })
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted() {
    this.getConcentrator(1, 100)
    this.getList();
    this.getSelectProtocol();
    this.getConcentratorOption();
    this.treeWidth = this.$refs['tree']?.$el.offsetWidth - 15
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
    setTimeout(() => {
      this.getCollector(1, 100, this.concentratorIds)
    },2000)
  },
};
</script>

<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node {
    width: fit-content;
    min-width: var(--treeWidth);
  }

  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;

    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }
  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 23%;
  }
}
.form_query {
  width: 20%;
  text-align: right;
}
</style>
